package com.huhu.contact.slice;

import com.huhu.contact.ContactPersonAbility;
import com.huhu.contact.ResourceTable;
import com.huhu.contact.data.ContactData;
import com.huhu.contact.model.ContactBean;
import com.huhu.contact.provider.StickyContactProvider;
import com.huhu.contact.utils.ElementUtil;
import com.huhu.contact.utils.PreferenceUtils;
import com.huhu.contact.utils.Toast;

import com.huhu.contact.view.HeaderDecor;
import com.huhu.contact.view.SlideBar;
import com.huhu.contact.widget.controller.FormControllerManager;
import ohos.aafwk.ability.*;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.utils.TextTool;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.utils.net.Uri;
import ohos.utils.zson.ZSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.IntStream;

/**
 * The ContactPersonAbilitySlice, the first page of app
 */
public class ContactPersonAbilitySlice extends AbilitySlice {
    protected static final HiLogLabel loglabel = new HiLogLabel(HiLog.LOG_APP, 0x11110, "ContactPersonAbilitySlice");
    // Button number on the bottom
    private static final int BOTTOM_TAB_BUTTON_NUM = 4;

    private ContactData categoryData;

    private TextField searchTextField;
    private ListContainer contactList;
    //    private LetterView letterView;
    private SlideBar slideBar;
    private StickyContactProvider mStickyContactProvider;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_contact_person);

        this.getWindow().setStatusBarColor(ElementUtil.getColor(this, ResourceTable.Color_colorSubBackground));
        this.getWindow().setNavigationBarColor(ElementUtil.getColor(this, ResourceTable.Color_colorSubBackground));

        categoryData = ContactData.get();
        categoryData.sortContactData();
        initView();
        initListener();
        initBottomTab();
    }

    /**
     * The initView, get component from xml
     */
    private void initView() {
        // Init component
        searchTextField = (TextField) findComponentById(ResourceTable.Id_searchTextField);
//        letterView = (LetterView) findComponentById(ResourceTable.Id_letterView);
        slideBar = (SlideBar) findComponentById(ResourceTable.Id_slideBar);

        searchTextField.setTextAlignment(TextAlignment.START | TextAlignment.VERTICAL_CENTER);
        if (TextTool.isLayoutRightToLeft(Locale.getDefault())) {
            searchTextField.setLayoutDirection(Component.LayoutDirection.RTL);
        } else {
            searchTextField.setLayoutDirection(Component.LayoutDirection.LTR);
        }

        contactList = (ListContainer) findComponentById(ResourceTable.Id_contactList);
        Text headerText = (Text) findComponentById(ResourceTable.Id_sticky_text);
        List<ContactBean> dataList = categoryData.getResultList();

        mStickyContactProvider = new StickyContactProvider(this, dataList);
        contactList.setItemProvider(mStickyContactProvider);
        HeaderDecor headerDecor = new HeaderDecor(contactList, headerText);

    }


    /**
     * The initListener, set listener of component
     */
    private void initListener() {
        findComponentById(ResourceTable.Id_add).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                categoryData.addContactBean("胡六一", "15269856587");
                categoryData.sortContactData();
                mStickyContactProvider.setDataListChanged(categoryData.getResultList());
            }
        });
        findComponentById(ResourceTable.Id_setUrgent).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
//                Operation operation = new Intent.OperationBuilder().withDeviceId("")
//                        .withBundleName(getBundleName())
//                        .withAbilityName("com.huhu.contact.UrgentAbility")
//                        .build();
//                Intent intent = new Intent();
//                intent.setOperation(operation);
//                startAbility(intent);

                showUrgentDialog();

            }
        });
        findComponentById(ResourceTable.Id_reset).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                categoryData = ContactData.get();
                categoryData.sortContactData();
                mStickyContactProvider.setDataListChanged(categoryData.getResultList());
            }
        });
        searchTextField.setKeyEventListener(
                (component, keyEvent) -> {
                    if (keyEvent.isKeyDown() && keyEvent.getKeyCode() == KeyEvent.KEY_ENTER) {
                        Toast.makeToast(
                                ContactPersonAbilitySlice.this,
                                getString(ResourceTable.String_you_search) + searchTextField.getText(),
                                Toast.TOAST_SHORT)
                                .show();
                    }
                    return false;
                });
        contactList.setItemClickedListener((listContainer, component, position, l1) -> {
            ContactBean item = (ContactBean) listContainer.getItemProvider().getItem(position);
            new ToastDialog(this)
                    .setText("you clicked:" + item.getName())
                    .setAlignment(LayoutAlignment.CENTER)
                    .show();

        });
        contactList.setItemLongClickedListener((listContainer, component, position, id) -> {
            ContactBean item = (ContactBean) contactList.getItemProvider().getItem(position);
            if (item.getType() == ContactBean.ITEM_TYPE.ITEM_TYPE_CHARACTER.ordinal()) return false;
            showConfirmDialog(position, item);
            return false;
        });
//        letterView.setCharacterListener(new LetterView.CharacterClickListener() {
//            @Override
//            public void onTouchAssortListener(String s) {
//                Toast.makeToast(ContactPersonAbilitySlice.this, s, Toast.TOAST_SHORT).show();
//            }
//
//            @Override
//            public void clickCharacter(String s) {
//                Toast.makeToast(ContactPersonAbilitySlice.this, s, Toast.TOAST_SHORT).show();
//            }
//
//            @Override
//            public void clickArrow() {
//
//            }
//        });
        slideBar.setOnTouchAssortListener(new SlideBar.OnTouchAssortListener() {
            @Override
            public void onTouchAssortListener(String s) {
                HiLog.error(loglabel, s);
                if (categoryData.getScrollPosition(s) >= 0) {
                    contactList.scrollTo(categoryData.getScrollPosition(s));
                }
            }
        });

    }


    /**
     * The initBottomTab, init the bottomTab
     */
    private void initBottomTab() {
        DirectionalLayout bottomTab = (DirectionalLayout) findComponentById(ResourceTable.Id_bottom_tabMenu);
        List<DirectionalLayout> tabList = new ArrayList<>();
        IntStream.range(0, BOTTOM_TAB_BUTTON_NUM).forEach(count -> {
            // Use LayoutScatter to convert xml file into Component instance
            DirectionalLayout tab =
                    (DirectionalLayout)
                            LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_tab, bottomTab, false);
            Image buttonImage = (Image) tab.findComponentById(ResourceTable.Id_bottom_tab_button_image);
            if (buttonImage != null) {
                buttonImage.setScaleMode(Image.ScaleMode.STRETCH);
                if (count == BOTTOM_TAB_BUTTON_NUM - 1) {
                    buttonImage.setPixelMap(ResourceTable.Media_icon_actived);
                } else {
                    buttonImage.setPixelMap(ResourceTable.Media_icon_normal);
                }
            }
            Text buttonText = (Text) tab.findComponentById(ResourceTable.Id_bottom_tab_button_text);
            if (buttonText != null) {
                buttonText.setText(getString(ResourceTable.String_tab));
            }
            tab.setClickedListener(
                    component -> {
                        // Deselect all tabs in tab menu
                        for (DirectionalLayout btn : tabList) {
                            ((Image) btn.findComponentById(ResourceTable.Id_bottom_tab_button_image))
                                    .setPixelMap(ResourceTable.Media_icon_normal);
                        }

                        // Set seleted state on the clicked tab
                        ((Image) component.findComponentById(ResourceTable.Id_bottom_tab_button_image))
                                .setPixelMap(ResourceTable.Media_icon_actived);
                    });
            tabList.add(tab);
            bottomTab.addComponent(tab);
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void showConfirmDialog(int position, ContactBean item) {
        // Init dialog
        CommonDialog loginDialog = new CommonDialog(this);
        // Get component from xml
        Component layoutComponent =
                LayoutScatter.getInstance(this).parse(ResourceTable.Layout_second_confirm_dialog, null, false);
        Text dialogText = (Text) layoutComponent.findComponentById(ResourceTable.Id_dialog_text);
        Text dialogSubText = (Text) layoutComponent.findComponentById(ResourceTable.Id_dialog_sub_text);


        dialogText.setText("是否确认删除？");
        dialogSubText.setText("确认");
        dialogSubText.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                categoryData.deleteContactBeans(item);
                categoryData.sortContactData();
                mStickyContactProvider.setDataListChanged(categoryData.getResultList());
                loginDialog.destroy();
                ;
            }
        });

        loginDialog
                .setContentCustomComponent(layoutComponent)
                .setTransparent(true)
                .setSize(AttrHelper.vp2px(300, this), DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                .setAutoClosable(true);

        loginDialog.show();
    }

    /**
     * The showLoginDialog, show the result of login whether success or fail, can clicked outside to cancel the dialog
     */
    private void showUrgentDialog() {
        // Init dialog
        CommonDialog loginDialog = new CommonDialog(this);
        // Get component from xml
        Component layoutComponent =
                LayoutScatter.getInstance(this).parse(ResourceTable.Layout_ability_urgent, null, false);
        TextField nameTf1 = (TextField) layoutComponent.findComponentById(ResourceTable.Id_nameTf1);
        TextField phoneTf1 = (TextField) layoutComponent.findComponentById(ResourceTable.Id_phoneTf1);
        TextField nameTf2 = (TextField) layoutComponent.findComponentById(ResourceTable.Id_nameTf2);
        TextField phoneTf2 = (TextField) layoutComponent.findComponentById(ResourceTable.Id_phoneTf2);
        Button confirm = (Button) layoutComponent.findComponentById(ResourceTable.Id_confirm);
        confirm.setEnabled(false);
        Button cancel = (Button) layoutComponent.findComponentById(ResourceTable.Id_cancel);
        phoneTf1.addTextObserver((text, i, i1, i2) -> {
            if (!text.isEmpty() && !phoneTf2.getText().isEmpty()) {
                confirm.setEnabled(true);
                confirm.setAlpha(1.0f);
            } else {
                confirm.setEnabled(false);
                confirm.setAlpha(0.5f);
            }
        });
        phoneTf2.addTextObserver((text, i, i1, i2) -> {
            if (!text.isEmpty() && !phoneTf1.getText().isEmpty()) {
                confirm.setEnabled(true);
                confirm.setAlpha(1.0f);
            } else {
                confirm.setEnabled(true);
                confirm.setAlpha(0.5f);
            }
        });
        confirm.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                ZSONObject zsonObject = new ZSONObject();
                zsonObject.put("urgent1", nameTf1.getText());
                zsonObject.put("urgentPhone1", phoneTf1.getText());
                zsonObject.put("urgent2", nameTf2.getText());
                zsonObject.put("urgentPhone2", phoneTf2.getText());
                PreferenceUtils.putString(getContext(),"urgentPerson", ZSONObject.toZSONString(zsonObject));
                FormBindingData formBindingData = new FormBindingData(zsonObject);
                ((ContactPersonAbility) getAbility()).confirmUpdateForm(formBindingData);
                loginDialog.destroy();

            }
        });
        cancel.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                loginDialog.destroy();
            }
        });

        loginDialog
                .setContentCustomComponent(layoutComponent)
                .setTransparent(true)
                .setSize(AttrHelper.vp2px(300, this), DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                .setAutoClosable(true);

        loginDialog.show();
    }
}


